import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/message.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/pages/message/message_query_model.dart';
import 'package:mall/core/providers/pages/message/message_view_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MessagePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => MessageQueryModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => MessageViewModel(context.read<Api>())),
      ],
      child: Consumer<MessageQueryModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget();
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    MessageQueryModel model = Provider.of(context, listen: false);
    List<Message> list = model.list;
    List<Message> messages = model.messages;
    return Scaffold(
      appBar: AppBar(
        title: Text('消息'),
      ),
      body: SmartRefresher(
        controller: _refreshController,
        child: ListView.separated(
          itemBuilder: (context, index) {
            return _MessageItemWidget(
              message: list[index],
            );
          },
          separatorBuilder: (context, index) {
            return SizedBox(
              height: 8.w,
            );
          },
          itemCount: list.length,
        ),
        enablePullDown: false,
        enablePullUp: messages.length == 10,
        onLoading: () {
          _onLoadData(context);
        },
      ),
    );
  }

  void _onLoadData(BuildContext context) async {
    MessageQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _MessageItemWidget extends StatelessWidget {
  final Message message;

  const _MessageItemWidget({
    Key key,
    @required this.message,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      child: InkWell(
        child: Container(
          padding: EdgeInsets.all(12.w),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      message.createTime,
                      style: TextStyle(fontSize: 14),
                    ),
                  ),
                  Text(message.viewed ? '已阅' : '未阅')
                ],
              ),
              SizedBox(height: 8.w),
              Text("${message.message}"),
              SizedBox(height: 8.w),
              Row(
                children: [
                  Expanded(
                    child: Text(
                      "${message.msgTypeName}",
                      style: TextStyle(color: Colors.grey, fontSize: 13),
                    ),
                  ),
                  if (message.enableSm)
                    Text(
                      message.send ? '已发短信' : '未发短信',
                      style: TextStyle(color: Colors.grey, fontSize: 13),
                    ),
                ],
              )
            ],
          ),
        ),
        onTap: message.viewed
            ? null
            : () {
                _onItemClicked(context);
              },
      ),
    );
  }

  void _onItemClicked(BuildContext context) async {
    MessageViewModel model = Provider.of(context, listen: false);
    var viewState = await model.messageView(message.id);
    switch (viewState) {
      case ViewState.busy:
        break;
      default:
        EasyLoading.showToast('已阅');
        MessageQueryModel messageQueryModel = Provider.of(context, listen: false);
        messageQueryModel.refreshData();
        break;
    }
  }
}
